SOURCES = $(wildcard *.c)
LPAR = \(
RPAR = \)
TARGET := $(shell grep -E -l '^[^/]*int[[:space:]]*main[[:space:]]*$(LPAR)[^$(RPAR)]*$(RPAR)' $(SOURCES))
TARGET := $(TARGET:%.c=%)
SUBDIRS := $(shell ls -R1F | grep "^\./" | sed -e "s/:$$//" -e "s/^\.\///")
SOURCES += $(foreach dir,$(SUBDIRS),$(wildcard $(dir)/*.c))
HEADERS = $(wildcard *.h)
HEADERS += $(foreach dir,$(SUBDIRS),$(wildcard $(dir)/*.h))
OBJECTS = $(SOURCES:.c=.o)
THIS_MAKEFILE := $(lastword $(MAKEFILE_LIST))

.PHONY : clean dist docs

LIBS = -lm
CC = gcc
CFLAGS = -g -Wall -pedantic \
-ansi \
-Waggregate-return \
-Wbad-function-cast \
-Wcast-qual \
-Wcast-align \
-Wdeclaration-after-statement \
-Wendif-labels \
-Werror \
-Wextra \
-Wfloat-equal \
-Wimport \
-Winline \
-Winvalid-pch \
-Wlong-long \
-Wmissing-declarations \
-Wmissing-field-initializers \
-Wmissing-format-attribute \
-Wmissing-noreturn \
-Wmissing-prototypes \
-Wnested-externs \
-Wold-style-definition \
-Wpacked \
-Wpointer-arith \
-Wpointer-sign \
-Wredundant-decls \
-Wshadow \
-Wsign-compare \
-Wstrict-prototypes \
-Wundef \
-Wunreachable-code \
-Wunused-macros \
-Wvariadic-macros \
-Wwrite-strings\
-Wformat

all: $(TARGET)

clean:
	rm -f $(TARGET) $(OBJECTS) .depend 

distclean:
	rm -f $(TARGET) $(OBJECTS) .depend *~ *.tgz

-include .depend

.depend: $(SOURCES) $(HEADERS)
	gcc -MM $(SOURCES) $(HEADERS) >.depend

$(TARGET): $(OBJECTS) 
	$(CC) -o $@ $(OBJECTS) $(CFLAGS) $(LIBS)

dist: clean
	tar -czvf $(TARGET).tgz $(SOURCES) $(HEADERS) $(THIS_MAKEFILE)
	
docs: .docs
	
.docs: $(SOURCES) $(HEADERS) ./docs/Doxyfile
	cd docs && doxygen Doxyfile && cd latex && $(MAKE) && mv *.pdf .. && touch ../../.docs

docsclean:
	rm .docs && cd docs && rm -R html latex *.pdf
